package com.hy.ruiji.controller;

import com.hy.ruiji.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * 文件的上传和下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${file.path}")
    private String BasePath;

    /**
     * 文件的上传
     * @param file 需要上传的文件
     * @return 返回文件名称
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() +s;
        //创建一个目录对象
        File dir=new File(BasePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            file.transferTo(new File(BasePath+fileName));
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件的下载
     * @param name 需要下载的名字
     * @param response 通过response输出流回写文件
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //通过输入流获取文件的内容
            FileInputStream fileInputStream = new FileInputStream(BasePath+name);
            //通过输出流把文件回写到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //定义文件的格式为图片
            response.setContentType("images/jpeg");
            int lens=0;
            byte[] bytes = new byte[1024];
            while ((lens=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,lens);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
